using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Windows.Interop;

namespace DesktopHelper.Services
{
    public class HotkeyService
    {
        private readonly ILogger<HotkeyService> _logger;
        private readonly ClipboardService _clipboardService;
        private readonly ScreenshotService _screenshotService;
        private readonly Dictionary<int, HotkeyAction> _registeredHotkeys = new();
        private HwndSource? _hwndSource;
        private int _hotkeyId = 1000;

        // Windows API 常量
        private const int WM_HOTKEY = 0x0312;
        private const int MOD_CONTROL = 0x0002;
        private const int MOD_SHIFT = 0x0004;
        private const int MOD_ALT = 0x0001;

        public HotkeyService(
            ILogger<HotkeyService> logger,
            ClipboardService clipboardService,
            ScreenshotService screenshotService)
        {
            _logger = logger;
            _clipboardService = clipboardService;
            _screenshotService = screenshotService;
        }

        public void RegisterHotkeys()
        {
            try
            {
                // 确保在UI线程上创建HwndSource
                System.Windows.Application.Current.Dispatcher.Invoke(() =>
                {
                    // 创建HwndSource参数
                    var parameters = new HwndSourceParameters("HotkeyListener")
                    {
                        Width = 0,
                        Height = 0,
                        WindowStyle = 0,
                        ExtendedWindowStyle = 0,
                        WindowClassStyle = 0,
                        UsesPerPixelOpacity = false
                    };

                    // 创建HwndSource
                    _hwndSource = new HwndSource(parameters);
                    if (_hwndSource == null || _hwndSource.Handle == IntPtr.Zero)
                    {
                        _logger.LogError("无法创建快捷键HwndSource");
                        return;
                    }
                    
                    _hwndSource.AddHook(WndProc);

                    // 注册默认热键
                    RegisterDefaultHotkeys();

                    _logger.LogInformation("全局快捷键已注册");
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "注册全局快捷键失败");
                throw; // 重新抛出异常以便上层捕获
            }
        }

        private void RegisterDefaultHotkeys()
        {
            // Ctrl + 1: 显示剪贴板历史
            RegisterHotkey(MOD_CONTROL, Keys.D1, () =>
            {
                ShowClipboardHistory();
            });

            // Ctrl + Shift + A: 区域截图
            RegisterHotkey(MOD_CONTROL | MOD_SHIFT, Keys.A, () =>
            {
                _screenshotService.CaptureRegion();
            });

            // Ctrl + Shift + W: 窗口截图
            RegisterHotkey(MOD_CONTROL | MOD_SHIFT, Keys.W, () =>
            {
                var screenshot = _screenshotService.CaptureActiveWindow();
                if (screenshot != null)
                {
                    _screenshotService.CaptureAndPin(screenshot);
                }
            });

            // Ctrl + Shift + S: 全屏截图
            RegisterHotkey(MOD_CONTROL | MOD_SHIFT, Keys.S, () =>
            {
                var screenshot = _screenshotService.CaptureFullScreen();
                _screenshotService.CaptureAndPin(screenshot);
            });

            // Ctrl + Shift + H: 显示/隐藏所有钉图
            RegisterHotkey(MOD_CONTROL | MOD_SHIFT, Keys.H, () =>
            {
                ToggleAllPinnedImages();
            });
        }

        private bool RegisterHotkey(int modifiers, Keys key, Action action)
        {
            try
            {
                var id = _hotkeyId++;
                if (NativeMethods.RegisterHotKey(_hwndSource!.Handle, id, (uint)modifiers, (uint)key))
                {
                    _registeredHotkeys[id] = new HotkeyAction { Action = action, Modifiers = modifiers, Key = key };
                    _logger.LogDebug("注册快捷键成功: {Modifiers}+{Key}", GetModifierString(modifiers), key);
                    return true;
                }
                else
                {
                    _logger.LogWarning("注册快捷键失败: {Modifiers}+{Key}", GetModifierString(modifiers), key);
                    return false;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "注册快捷键异常: {Modifiers}+{Key}", GetModifierString(modifiers), key);
                return false;
            }
        }

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == WM_HOTKEY)
            {
                var hotkeyId = wParam.ToInt32();
                if (_registeredHotkeys.TryGetValue(hotkeyId, out var hotkeyAction))
                {
                    try
                    {
                        hotkeyAction.Action?.Invoke();
                        handled = true;
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "执行快捷键动作失败: {HotkeyId}", hotkeyId);
                    }
                }
            }
            return IntPtr.Zero;
        }

        private void ShowClipboardHistory()
        {
            try
            {
                System.Windows.Application.Current.Dispatcher.Invoke(() =>
                {
                    // 显示剪贴板历史窗口
                    var historyWindow = new Views.ClipboardHistoryWindow();
                    
                    // 设置窗口位置在鼠标附近
                    var mousePos = System.Windows.Forms.Control.MousePosition;
                    historyWindow.Left = mousePos.X - 150;
                    historyWindow.Top = mousePos.Y - 200;
                    
                    // 确保窗口在屏幕范围内
                    var screenBounds = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
                    if (historyWindow.Left < 0) historyWindow.Left = 10;
                    if (historyWindow.Top < 0) historyWindow.Top = 10;
                    if (historyWindow.Left + historyWindow.Width > screenBounds.Width)
                        historyWindow.Left = screenBounds.Width - historyWindow.Width - 10;
                    if (historyWindow.Top + historyWindow.Height > screenBounds.Height)
                        historyWindow.Top = screenBounds.Height - historyWindow.Height - 10;
                    
                    historyWindow.WindowState = System.Windows.WindowState.Normal;
                    historyWindow.Show();
                    historyWindow.Activate();
                    historyWindow.Focus();
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "显示剪贴板历史失败");
            }
        }

        private void ToggleAllPinnedImages()
        {
            try
            {
                // 这里需要与PinnedImageService协作
                // 暂时留空，后续实现
                _logger.LogDebug("切换所有钉图显示状态");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "切换钉图显示状态失败");
            }
        }

        private string GetModifierString(int modifiers)
        {
            var parts = new List<string>();
            if ((modifiers & MOD_CONTROL) != 0) parts.Add("Ctrl");
            if ((modifiers & MOD_SHIFT) != 0) parts.Add("Shift");
            if ((modifiers & MOD_ALT) != 0) parts.Add("Alt");
            return string.Join("+", parts);
        }

        public void UnregisterAllHotkeys()
        {
            try
            {
                if (_hwndSource != null)
                {
                    foreach (var hotkeyId in _registeredHotkeys.Keys)
                    {
                        NativeMethods.UnregisterHotKey(_hwndSource.Handle, hotkeyId);
                    }
                    _registeredHotkeys.Clear();

                    _hwndSource.RemoveHook(WndProc);
                    _hwndSource.Dispose();
                    _hwndSource = null;
                }

                _logger.LogInformation("所有快捷键已注销");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "注销快捷键失败");
            }
        }

        public void Dispose()
        {
            UnregisterAllHotkeys();
        }
    }

    // 快捷键动作类
    internal class HotkeyAction
    {
        public Action? Action { get; set; }
        public int Modifiers { get; set; }
        public Keys Key { get; set; }
    }

    // Windows API 声明
    internal static partial class NativeMethods
    {
        [DllImport("user32.dll")]
        internal static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

        [DllImport("user32.dll")]
        internal static extern bool UnregisterHotKey(IntPtr hWnd, int id);
    }
}